package org.javaymw.springboot.controller;

import org.apache.commons.lang3.RandomStringUtils;
import org.javaymw.springboot.base.BaseController;
import org.javaymw.springboot.service.MemberService;
import org.javaymw.springboot.util.MessageUtils;
import org.javaymw.springboot.vo.MemberVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.Context;

import java.util.Map;

/**
 * @Auther: zhaoxinguo
 * @Date: 2018/7/30 18:49
 * @Description: 短信验证码
 */
@Controller
@RequestMapping(value = "/phone")
public class PhoneController extends BaseController {

    @Autowired
    private MemberService memberService;

//    @Autowired
//    private CustomerInfoPublisher customerInfoPublisher;

    /**
     * 校验手机号是否存在
     * @param phone
     * @return
     */
    @GetMapping("/check")
    @ResponseBody
    public Map<String, Object> check(@RequestParam("phone") String phone) {
        Map<String, Object> retMap = null;
        try {
            if (memberService.getMemberCountByPhone(phone) > 0) {
                retMap = MessageUtils.success();
            } else {
                retMap = MessageUtils.error("手机号不存在，请输入注册时候的手机号");
            }
        } catch (Exception e) {
            retMap = MessageUtils.error();
        }
        return retMap;
    }

    /**
     * 发送短信验证码
     * @param to
     * @return
     */
    @GetMapping("/code")
    @ResponseBody
    public Map<String, Object> code(@RequestParam("to") String to) {
        Map<String, Object> retMap = null;
        try {
            // 解析模板并发送
            Context context = new Context();
            // 生成短信验证码
            String code = getSmsCode();
            // 把短信验证码(key)，短信验证码(value)放到缓存里面
            context.setVariable("code", code);
            String smsContent = "【迷彩风情】尊敬的用户，你的验证码是：【#"+code+"#】，请在10分钟内输入。请勿告诉其他人。";
            MemberVo memberVo = new MemberVo();
            // 提交发送短信验证码事件
            /*eventPublisher.publishEvent(new OnSendSmsEvent(memberVo, to, smsContent));*/
            // 提交发送短信验证码消息到Redis队列
//            customerInfoPublisher.publish(to + "-" + smsContent);
            retMap = MessageUtils.success("验证码已经发送到您的手机，请注意查收");
        } catch (Exception e) {
            retMap = MessageUtils.error();
        }
        return retMap;
    }

    private String getSmsCode() {
        synchronized (this) {
            // 生成4位随机验证码
            String smsCode = RandomStringUtils.random(4,"0123456789");
            // 把短信验证码放入本地缓存
            cacheManager.getCache("SmsCodeCache").put("smsCode", smsCode);
            return smsCode;
        }
    }
}
